from copy import deepcopy
from tkinter import StringVar
from tkinter.simpledialog import Dialog
from tkinter.ttk import Frame, Button, Label, Entry
from .style import PADDING
from .event_bus import ETYPE_TAG_CHANGED, Event, send_event
from ..store.tag import Tag, EMPTY_TAG, add_tag, update_tag, get_tag_by_name

PADDING_D_2 = PADDING // 2

class TagDialog(Dialog):
    def __init__(self, parent, old_tag: Tag = EMPTY_TAG):
        self.old_tag = deepcopy(old_tag)
        super().__init__(parent, "添加标签" if self.is_adding_tag else "编辑标签")
    
    @property
    def is_adding_tag(self):
        return self.old_tag.uid < 0
    
    def body(self, _master):
        self.resizable(False, False)
        box = Frame(self)
        # 标签名字
        frame = Frame(box)
        label = Label(frame, text="标签名称")
        label.pack(side="left", padx=(0, PADDING_D_2))
        self.tag_name_var = StringVar()
        self.tag_name_var.set(self.old_tag.name)
        tag_name = Entry(frame, width=64, textvariable=self.tag_name_var)
        tag_name.pack(side="right")
        frame.pack(side="top", padx=PADDING, pady=(PADDING, 0), fill="x")
        # 标签关键字
        frame = Frame(box)
        label = Label(frame, text="标签关键字")
        label.pack(side="left", padx=(0, PADDING_D_2))
        self.tag_kws_var = StringVar()
        self.tag_kws_var.set(" ".join(self.old_tag.kws))
        tag_kws = Entry(frame, width=64, textvariable=self.tag_kws_var)
        tag_kws.pack(side="right")
        frame.pack(side="top", padx=PADDING, pady=(PADDING, 0), fill="x")
        box.pack(side="top", padx=0, pady=0)

    def buttonbox(self):
        box = Frame(self)
        w = Button(box, text="保存", width=10, command=self.ok, default="active")
        w.pack(side="left", padx=PADDING_D_2, pady=(0, PADDING))
        w = Button(box, text="取消", width=10, command=self.cancel)
        w.pack(side="right", padx=PADDING_D_2, pady=(0, PADDING))
        box.pack()

    def validate(self):
        name = self.tag_name_var.get().strip()
        if len(name) <= 0:
            #名字为空
            return False
        if self.is_adding_tag:
            if get_tag_by_name(name):
                # 名字已经存在了
                return False
        return True

    def apply(self):
        tag = Tag()
        tag.uid = self.old_tag.uid
        tag.name = self.tag_name_var.get().strip()
        tag.kws = set(self.tag_kws_var.get().strip().split(" "))
        if self.is_adding_tag:
            add_tag(tag)
        else:
            update_tag(tag)
        send_event(Event(t=ETYPE_TAG_CHANGED))